package bili

import (
	"context"
	"fmt"
	"github.com/chromedp/cdproto/network"
	"github.com/chromedp/cdproto/target"
	"github.com/chromedp/chromedp"
	"github.com/sirupsen/logrus"
	"time"
)

type BiLStruct struct {
	url    string
	ctx    context.Context
	cancel context.CancelFunc
}

func NewBls(boo bool) *BiLStruct {
	s := &BiLStruct{
		url: "https://www.bilibili.com/",
	}
	fmt.Println("我是测试的diamagnetic")
	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("headless", boo), // 是否打开浏览器调试
		chromedp.UserAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"), // 设置User-Agent
	}
	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
	// chromdp依赖context上限传递参数
	s.ctx, s.cancel = chromedp.NewExecAllocator(
		context.Background(),
		options...,
	)
	s.ctx, s.cancel = chromedp.NewContext(
		s.ctx,
	)
	return s
}

func (s *BiLStruct) Start() error {
	err := chromedp.Run(s.ctx,
		// 监听页面
		chromedp.ActionFunc(func(ctx context.Context) error {
			chromedp.ListenTarget(s.ctx, func(ev interface{}) {
				switch e := ev.(type) {
				case *network.EventResponseReceived:
					go func() {
						switch e.Type {
						case network.ResourceTypeDocument:
							logrus.Debug("打开页面：", e.Response.URL)
						case network.ResourceTypeXHR:
							logrus.Debug("请求 ajax 接口：", e.Response.URL)
						case network.ResourceTypeWebSocket:
							logrus.Debug("websocket：", e.Response.URL)
						case network.ResourceTypeFetch:
							logrus.Debug("请求 fetch 接口：", e.Response.URL)
						default:
							//	logrus.Debug("暂时用不到的其他类型请求：", e.RequestID.String())
						}
					}()
				}
			})
			return nil
		}),
		// 打开画面
		chromedp.Navigate(s.url),
		s.ListenQuit(),
		// 等待新页面打开，然后将其注册到上下文中
		chromedp.ActionFunc(func(ctx context.Context) error {
			go func() {
				// 等待新页面打开
				ch := chromedp.WaitNewTarget(s.ctx, func(info *target.Info) bool {
					logrus.Debugf("打开新页面,url: %s,TargetID:%s", info.URL, info.TargetID)
					return info.URL != ""
				})
				// 将新开页面设置到上下文中
				s.ctx, s.cancel = chromedp.NewContext(s.ctx, chromedp.WithTargetID(<-ch))
			}()
			return nil
		}),
		// 点击登录按钮
		s.ClickLogin(),
	)
	return err
}

func (s *BiLStruct) ClickLogin() chromedp.ActionFunc {
	return func(ctx context.Context) error {
		return chromedp.Run(s.ctx,
			chromedp.Sleep(1*time.Second),
			chromedp.Click(`document.getElementsByClassName("header-login-entry")[0]`, chromedp.ByJSPath),
		)
	}
}
func (s *BiLStruct) ListenQuit() chromedp.ActionFunc {
	return func(ctx context.Context) error {
		logrus.Debugf("等待用户登录......")
		for {
			select {
			case <-s.ctx.Done():
				logrus.Info("浏览器被关闭，退出进程")
				return nil
			default:
			}
		}
		return nil
	}
}
